<template>
	<view>
		<!--popup弹窗-->
		<uni-popup ref="openDetail" type="center">
			<view class="open-detail">
				<!--类型-->
				<view class="open-detail-item">
					<view class="content">
						<view class="canvas">
							<canvas class="canvas" @click.stop="saveImage" :style="{ width: canvasW + 'px', height: canvasH + 'px' }" canvas-id="my-canvas"></canvas>
						</view>
						<view class="save-btn" v-if="btnShow" @click.stop="saveImage">保存图片</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default{
		props:{
			shareType: { //海报类型 home:首页 detail:详情页 注意：生成首页功能还未完成，请勿使用
				type: String,
				default: 'detail'
			},
			headerImg:{
				type: String,
				default: ''
			},
			title:{
				type: String,
				default: '标题'
			},
			subTitle:{
				type: String,
				default: '副标题'
			},
			price:{
				type: String,
				default: '0'
			},
			abImg:{
				type: String,
				default: ''
			},
		},
		data(){
			return {
				canvasW: 0,
				canvasH: 0,
				ctx: null,
				btnShow: false, // 显示保存按钮
				qrcode: '',
				currentPrice: this.price
			}
		},
		created() {
			console.log(this.qrcode)
		},
		methods:{
			//显示
			showCanvas(qrcode){
				
				this.qrcode = qrcode
				if(this.btnShow == true){
					this.$refs.openDetail.open()
				}else{
					this.__init()
					this.$refs.openDetail.open()
				}
				
			},
			//初始化画布
			async __init(){
				uni.showLoading({
				    title: '加载中...',
					mask: true
				})
				this.ctx = uni.createCanvasContext('my-canvas',this)
				//this.canvasW = uni.upx2px(580);
				//this.canvasH = uni.upx2px(800);
				this.canvasW = 280
				this.canvasH = 430
				//设置画布背景透明
				this.ctx.setFillStyle('rgba(255, 255, 255, 0)')
				//设置画布大小
				this.ctx.fillRect(0,0,this.canvasW,this.canvasH)
				//绘制圆角背景
				this.drawRoundRect(this.ctx, 0, 0, this.canvasW, this.canvasH,uni.upx2px(18),'#FFFFFF')
				//获取封面图片
				let headerImg = await this.getImageInfo(this.headerImg)
				let hW = 0
				let hH = 0
				//console.log(this.shareType)
				if(this.shareType == 'detail'){
					console.log('绘制详情页')
					hW = 260
					hH = 180
					//绘制封面图
					this.drawRoundImg(this.ctx,headerImg.path,((this.canvasW-hW) / 2),((this.canvasW-hW) / 2),hW,hH,8)
				}
				if(this.shareType == 'home'){
					console.log('绘制首页')
					hW = 120
					hH = 120
					//绘制封面图
					this.drawRoundImg(this.ctx,headerImg.path,((this.canvasW-hW) / 2),20,hW,hH,8)
				}
				
				//绘制标题
				this.ctx.setFontSize(18); //设置标题字体大小
				this.ctx.setFillStyle('#333'); //设置标题文本颜色
				//this.ctx.fillText(this.title,((this.canvasW-hW) / 2),(((this.canvasW-hW) / 2) + hH + 30))
				if(this.shareType == 'detail'){
					this.drawText(this.ctx, this.title, ((this.canvasW-hW) / 2), (((this.canvasW-hW) / 2) + hH + 30), 30, 258);// 调用行文本换行函数
				}
				if(this.shareType == 'home'){
					this.drawText(this.ctx, this.title, 20, 180, 30, 258);// 调用行文本换行函数
				}
				//绘制副标题
				this.ctx.setFontSize(14);
				this.ctx.setFillStyle('#858585');
				let sWidth = this.ctx.measureText(this.subTitle).width
				if(sWidth > hW){
					this.ctx.fillText(this.subTitle.slice(0,19) + '...',((this.canvasW-hW) / 2),(
					((this.canvasW-hW) / 2) + hH + 70))
				}else{
					this.ctx.fillText(this.subTitle,((this.canvasW-hW) / 2),(
					((this.canvasW-hW) / 2) + hH + 70))
				}
				//绘制价格
				if(this.shareType == 'detail'){
					this.ctx.setFontSize(14);
					this.ctx.setFillStyle('#f54545');
					this.ctx.fillText('￥',((this.canvasW-hW) / 2),(((this.canvasW-hW) / 2) + hH + 95))
					this.ctx.setFontSize(18);
					if(this.currentPrice == '0') this.currentPrice = '免费'
					this.ctx.fillText(this.currentPrice,(((this.canvasW-hW) / 2) + 18),(((this.canvasW-hW) / 2) + hH + 95))
				}
				
				//绘制虚线
				this.drawDashLine(this.ctx,10,(((this.canvasW-hW) / 2) + hH + 120),(this.canvasW-10),(((this.canvasW-hW) / 2) + hH + 120),5)
				//左边实心圆
				this.drawEmptyRound(this.ctx,0,(((this.canvasW-hW) / 2) + hH + 120),10)
				//右边实心圆
				this.drawEmptyRound(this.ctx,this.canvasW,(((this.canvasW-hW) / 2) + hH + 120),10)
				//提示文案
				this.ctx.setFontSize(12);
				this.ctx.setFillStyle('#858585');
				this.ctx.fillText('长按识别图中小程序',10,(((this.canvasW-hW) / 2) + hH + 150))
				//底部广告
				let BottomAdImg = await this.getImageInfo(this.abImg)
				this.ctx.drawImage(BottomAdImg.path,10,(((this.canvasW-hW) / 2) + hH + 160),55,55)
				//小程序码
				let qrcodeImg = await this.getImageInfo(this.qrcode)
				this.ctx.drawImage(qrcodeImg.path,180,(((this.canvasW-hW) / 2) + hH + 135), 92, 92)
				//延迟渲染
				setTimeout(()=>{
					this.ctx.draw(true,()=>{
						uni.hideLoading()
					})
					this.btnShow = true
				},500)
			},
			//绘制实心圆
			drawEmptyRound(ctx,x,y,radius){
				ctx.save()
				ctx.beginPath();
				ctx.arc(x, y, radius, 0, 2 * Math.PI,true);
				ctx.setFillStyle('rgba(0, 0, 0, .4)')
				ctx.fill();
				ctx.restore()
				ctx.closePath()
			},
			//绘制虚线
			drawDashLine(ctx,x1,y1,x2,y2,dashLength){
				ctx.setStrokeStyle("#cccccc")//设置线条的颜色
				ctx.setLineWidth(1)//设置线条宽度
				var dashLen = dashLength,
				xpos = x2 - x1, //得到横向的宽度;
				ypos = y2 - y1, //得到纵向的高度;
				numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen); 
				//利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
				for(var i=0; i<numDashes; i++){
				 if(i % 2 === 0){
					 ctx.moveTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i); 
					 //有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
				  }else{
					  ctx.lineTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i);
				  }
				}
				ctx.stroke();
			},
			//带圆角图片
			drawRoundImg(ctx, img, x, y, width, height, radius){
				ctx.beginPath()
				ctx.save()
				// 左上角
				ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
				// 右上角
				ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
				// 右下角
				ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
				// 左下角
				ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
				ctx.stroke()
				ctx.clip()
				ctx.drawImage(img, x, y, width, height);
				ctx.restore()
				ctx.closePath()
			},
			//圆角矩形
			drawRoundRect(ctx, x, y, width, height, radius, color){
				ctx.save();
				ctx.beginPath();
				ctx.setFillStyle(color); 
				ctx.setStrokeStyle(color)
				ctx.setLineJoin('round');  //交点设置成圆角
				ctx.setLineWidth(radius);
				ctx.strokeRect(x + radius/2, y + radius/2, width - radius , height - radius );
				ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2);
				ctx.stroke();
				ctx.closePath();
			},
			//获取图片
			getImageInfo(imgSrc){
				console.log(imgSrc)
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: imgSrc,
						success: (image) => {
							resolve(image);
							console.log('获取图片成功',image)
						},
						fail: (err) => {
							reject(err);
							console.log('获取图片失败',err)
						}
					});
				});
			},
			/**
			 * 绘制多行文本
			 * ctx canvas对象
			 * str 文本
			 * leftWidth 距离左侧的距离
			 * initHeight 距离顶部的距离
			 * titleHeight 文本的高度
			 * canvasWidth 文本的宽度
			 * @returns {*}
			 */
			drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
			    let lineWidth = 0;
			    let lastSubStrIndex = 0; //每次开始截取的字符串的索引
			    for (let i = 0; i < str.length; i++) {
			        lineWidth += ctx.measureText(str[i]).width;
			        if (lineWidth > canvasWidth) {
			            ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
			            initHeight += 22; //22为 文字大小20 + 2
			            lineWidth = 0;
			            lastSubStrIndex = i;
			            titleHeight += 22;
			        }
			        if (i == str.length - 1) { //绘制剩余部分
			            ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
			        }
			    }
			    // 标题border-bottom 线距顶部距离
			    titleHeight = titleHeight + 10;
			    return titleHeight;
			},

			//保存图片到相册
			saveImage(){
				//判断用户授权
				uni.getSetting({
				   success(res) {
				      console.log('获取用户权限',res.authSetting)
					  if(Object.keys(res.authSetting).length>0){
						  //判断是否有相册权限
						  if(res.authSetting['scope.writePhotosAlbum']==undefined){
							  //打开设置权限
							  uni.openSetting({
							    success(res) {
							      console.log('设置权限',res.authSetting)
							    }
							  })
						  }else{
							  if(!res.authSetting['scope.writePhotosAlbum']){
								  //打开设置权限
								  uni.openSetting({
								    success(res) {
								      console.log('设置权限',res.authSetting)
								    }
								  })
							  }
						  }
					  }else{
						  return
					  }
				   }
				})
				var that = this
				uni.canvasToTempFilePath({
					canvasId: 'my-canvas',
					quality: 1,
					complete: (res) => {
						console.log('保存到相册',res);
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(res) {
								uni.showToast({
									title: '已保存到相册',
									icon: 'success',
									duration: 2000
								})
							}
						})
					}
				},this);
			}
		}
	}
</script>

<style lang="scss">
.content{
	.canvas {
		
	}
	.save-btn{
		margin-top: 35rpx;
		color: #FFFFFF;
		background: linear-gradient(to right, #FE726B , #FE956B);
		padding: 15rpx 40rpx;
		border-radius: 50rpx;
		text-align: center;
	}
}
</style>
